package com.jobsika.client.post;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.jobsika.client.Util;
import com.jobsika.domain.RPCPost;

public class PostPanel extends Composite {
	private VerticalPanel skeleton;
	private HTML title;
	
	public PostPanel(final RPCPost post) {
		skeleton = new VerticalPanel();
		title		= new HTML(post.getTitle());
		String postLocation = post.getLocation().replaceAll("-", ", ");
		postLocation = postLocation.replaceAll("_", " ");
		
		Label location	= new Label(postLocation);
		Label date		= new Label(Util.dtf.format(post.getDate()));
		HTML body		= new HTML(post.getBody());
		
		skeleton.add(title);
		skeleton.add(date);
		skeleton.add(location);
		skeleton.add(new HTML("<br>"));
		skeleton.add(body);
		
		title.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				Window.Location.assign(post.getUrl().toString());
			}
		});
		title.addMouseOverHandler(titleMouseOver);
		title.addMouseOutHandler(titleMouseOut);
		title.setStyleName("postPanel-title");
		location.setStyleName("postPanel-item");
		date.setStyleName("postPanel-item");
		skeleton.setStyleName("postPanel");
		this.initWidget(skeleton);
		this.addKeyPressHandler(new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				char charcode = event.getCharCode();
				if (true) {
					switch (charcode) {
						case 106:
							getPrevious();
							break;
						case 107:
							getNext();
							break;
					}
				}
				Window.alert(charcode+"");
			}
		});
	}
	
	MouseOverHandler titleMouseOver = new MouseOverHandler() {
		@Override
		public void onMouseOver(MouseOverEvent event) {
			title.addStyleName("postPanel-title-over");
		}
	};
	
	MouseOutHandler titleMouseOut = new MouseOutHandler() {
		@Override
		public void onMouseOut(MouseOutEvent event) {
			title.removeStyleName("postPanel-title-over");
		}
	};
	
	private void getNext() {
		Window.alert("Next");
	}
	
	private void getPrevious() {
		Window.alert("Previous");
	}
	
	public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) {
		return addDomHandler(handler, KeyPressEvent.getType());
	}
}
